<?php
class CSalesActivity {
	var $sa_user;
	var $sa_date;
	var $sa_online_second = 0;
	var $sa_widget_view = 0;
	var $sa_sale_link_click = 0;
	var $sa_start_time;

	/**
	 * Constructor
	 *
	 * @param unknown_type $user_id
	 * @param unknown_type $date
	 */
	public function __construct($user_id, $date = null, $inc_second = 0, $inc_widget = 0, $inc_sale = 0, $start_time = -1) {
		$this->sa_user = $user_id;
		if ($date == null) $date = date('Y-m-d');
		$cache_name = 'act_'.$user_id;
		if ($ret = CSystem::$cachesession->get($cache_name)) {
			list($this->sa_date, $this->sa_online_second, $this->sa_widget_view, $this->sa_sale_link_click) = $ret;
			if (isset($ret[4])) {
				$this->sa_start_time = $ret[4];
			} else {
				$this->sa_start_time = 0;
			}
			if ($date != $this->sa_date) {
				$this->saveToDatabase();
				$this->sa_date = $date;
				$this->sa_online_second = 0;
				$this->sa_widget_view = 0;
				$this->sa_sale_link_click = 0;
			}
		}
		$this->sa_date = $date;
		if ($inc_second > 0 && $this->sa_start_time != $start_time) {
			$this->sa_online_second += $inc_second;
			if ($start_time != -1) $this->sa_start_time = $start_time;
		}
		$this->sa_widget_view += $inc_widget;
		$this->sa_sale_link_click += $inc_sale;
		$this->saveToCache($cache_name);
	}

	/**
	 * Enter description here...
	 *
	 */
	public function saveToDatabase() {
		CTable('sales_activity')->insert(array(
			'sa_user' => $this->sa_user,
			'sa_date' => $this->sa_date,
			'sa_online_second' => $this->sa_online_second,
			'sa_widget_view' => $this->sa_widget_view,
			'sa_sale_link_click' => $this->sa_sale_link_click
		));
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $cache_name
	 */
	public function saveToCache($cache_name) {
		CSystem::$cachesession->set($cache_name, array(
			$this->sa_date,
			$this->sa_online_second,
			$this->sa_widget_view,
			$this->sa_sale_link_click,
			$this->sa_start_time,
		), 3600*24*2);
	}
}